package com.usian.wemedia.gateway.filter;


import com.usian.jwt.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
public class WemediaGatewayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { //exchange交换机  chain  链路
        //1.获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        if (request.getURI().getPath().contains("/login/in")){//判断是不是登录接口,是就放行
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("token");//获取当前的token信息
        if (StringUtils.isEmpty(token)){ //判断token是否存在
            String json="{\"errorMessage\":\" not hava token \"}";
            return response.writeWith(Flux.just(response.bufferFactory().wrap(json.getBytes())));//返回错误信息
        }
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claimsBody);
        if (i== 0 || i== -1){
            Integer id = (Integer) claimsBody.get("id");
            ServerHttpRequest httpRequest = request.mutate()  //建造者模式   重构
                    .headers(HttpHeaders -> {
                        HttpHeaders.add("userId", id + "");
                    }).build();
            exchange.mutate().request(httpRequest).build();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
